<?php require "db.php"; ?>
<?php

    $architects = mysqli_query($con, "SELECT * FROM architects");

    $save = false;

    function saveImage($i){
        $allowedExts = array("gif", "jpeg", "jpg", "png");
        $extension = end(explode(".", $_FILES["images"]["name"][$i]));
        if ((($_FILES["images"]["type"] == "image/gif")
                || ($_FILES["images"]["type"][$i] == "image/jpeg")
                || ($_FILES["images"]["type"][$i] == "image/jpg")
                || ($_FILES["images"]["type"][$i] == "image/pjpeg")
                || ($_FILES["images"]["type"][$i] == "image/x-png")
                || ($_FILES["images"]["type"][$i] == "image/png"))
            && ($_FILES["images"]["size"][$i] < 1000000)
            && in_array($extension, $allowedExts))
        {
            if ($_FILES["images"]["error"][$i] > 0)
            {
                return false;
            }
            else
            {
                /*echo "Upload: " . $_FILES["images"]["name"][$i] . "<br>";
                echo "Type: " . $_FILES["images"]["type"][$i] . "<br>";
                echo "Size: " . ($_FILES["images"]["size"][$i] / 1024) . " kB<br>";
                echo "Temp file: " . $_FILES["images"]["tmp_name"][$i] . "<br>";*/

                if (file_exists("upload/" . $_FILES["images"]["name"][$i]))
                {
                    return true;
                }
                else
                {
                    move_uploaded_file($_FILES["images"]["tmp_name"][$i],
                        "upload/" . $_FILES["images"]["name"][$i]);
                    return true;
                    //echo "Stored in: " . "upload/" . $_FILES["images"]["name"][$i];
                }
            }
        }
        else
        {
            return false;
        }
    }

    if($_GET['id'] && $_GET['action'] == 'remove'){
        $ids = $_GET['id'];
        foreach($ids as $id){
            $query = mysqli_query($con, "DELETE FROM projects WHERE id=".$id);
        }
        header('Location: projects.php');
    }

    if($_POST['save']){
        $name = $_POST['name'];
        $cost = $_POST['cost'];
        $start_date = $_POST['start_date'];
        $finish_date = $_POST['finish_date'];
        $architect = $_POST['architect'];

        if($name && $cost && $start_date && $architect){
            if($_GET['id']){
                $query = mysqli_query($con, "UPDATE projects SET name='".$name."', cost=".$cost.", start_date='".$start_date."', ". ($finish_date ? "finish_date='".$finish_date."'," : "" )."
                                            architect_id='".$architect."' WHERE id=".$_GET['id'][0]);
                if($query == 1) {
                    if($_FILES && $_FILES['images'] && $_FILES['images']['name'])
                        foreach($_FILES['images']['name'] as $key => $image){
                            if(saveImage($key)){
                                $res = mysqli_query($con, "SELECT * FROM images WHERE name='".$_FILES['images']['name'][$key]."' AND project_id='".$_GET['id'][0]."'");
                                if(!mysqli_fetch_assoc($res)){
                                    $query = mysqli_query($con, "INSERT INTO images (name, project_id) VALUES ('".$_FILES['images']['name'][$key]."', ".$_GET['id'][0].")");
                                }
                            }
                        }
                    $save = true;
                }
            }else{
                $query = mysqli_query($con, "INSERT INTO projects (name, cost, start_date, ". ($finish_date ? "finish_date, " : ""  ) ." architect_id) VALUES
                                            ('".$name."',".$cost.", '".$start_date."', ". ($finish_date ? "'".$finish_date."', " : ""  ) ."  '".$architect."')");
                if($query == 1) {
                    if($_FILES && $_FILES['images'] && $_FILES['images']['name'])
                        foreach($_FILES['images']['name'] as $key => $image){
                            if(saveImage($key)){
                                $res = mysqli_query($con, "SELECT * FROM images WHERE name='".$_FILES['images']['name'][$key]."' AND project_id='".$_GET['id'][0]."'");
                                if(!mysqli_fetch_assoc($res)){
                                    $query = mysqli_query($con, "INSERT INTO images (name, project_id) VALUES ('".$_FILES['images']['name'][$key]."', ".mysql_insert_id().")");
                                }
                            }
                        }
                    $save = true;
                }
            }
        }
    }
    if($_GET['id']){
        $project = mysqli_query($con, "SELECT * FROM projects WHERE id=".$_GET['id'][0]);
        $images = mysqli_query($con, "SELECT * FROM images WHERE project_id=".$_GET['id'][0]);
        $data = mysqli_fetch_assoc($project);
    }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Admin Panel - Projects</title>
    <link href="css/bootstrap-responsive.css" rel="stylesheet" type="text/css" />
    <link href="css/bootstrap.css" rel="stylesheet" type="text/css" />
    <link href="css/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
    <header>
        <h3 class="muted">Admin Panel</h3>
        <div class="navbar">
            <div class="navbar-inner">
                <div class="container">
                    <ul class="nav">
                        <li>
                            <a href="index.php">Home</a>
                        </li>
                        <li class="dropdown active">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown">Projects <b class="caret"></b></a>
                            <ul class="dropdown-menu">
                                <li><a href="projects.php">View</a></li>
                                <li><a href="project.php">Add Project</a></li>
                            </ul>
                        </li>
                        <li class="dropdown">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown">Architects <b class="caret"></b></a>
                            <ul class="dropdown-menu">
                                <li><a href="architects.php">View</a></li>
                                <li><a href="architect.php">Add Architect</a></li>
                            </ul>
                        </li>
                        <li>
                            <a href="#">Settings</a>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </header>
    <section>
        <ul class="breadcrumb">
            <li><a href="index.php">Home</a> <span class="divider">/</span></li>
            <li><a href="projects.php">Projects</a> <span class="divider">/</span></li>
            <li class="active">Add Project</li>
        </ul>
        <form action="" method="POST" enctype="multipart/form-data">
        <div class="row-fluid">
            <div class="span8">
                <?php if($save){ ?>
                    <div class="alert alert-success"><strong>Well done!</strong> Item was saved successfully.</div>
                <?php }elseif($_POST['save']){ ?>
                    <div class="alert alert-error"><strong>Uppsss!</strong> Check out all field and fill them.</div>
                <?php } ?>
            </div>
            <div class="span4 text-right">
                <button type="submit" name="save" value="1" class="btn btn-primary">Save</button>
                <button type="reset" class="btn btn-warning">Clear</button>
            </div>
        </div>
        <hr />
        <div>
            <div class="control-group  <?php if($_POST['save'] && !$name) echo "error"; ?>">
                <label class="control-label" for="inputName">Name</label>
                <div class="controls">
                    <input type="text" name="name" class="input-xlarge" id="inputName" value="<?php echo $data['name'];?>" placeholder="Project Name">
                    <?php if($_POST['save'] && !$name) { ?>
                        <span class="help-inline">Please correct the error</span>
                    <?php } ?>
                </div>
            </div>
            <div class="row-fluid">
                <div class="span4">
                    <div class="control-group <?php if($_POST['save'] && !$start_date) echo "error"; ?>">
                        <label class="control-label" for="inputStartDate">Start Date</label>
                        <div class="controls">
                            <input type="date" name="start_date" id="inputStartDate" value="<?php echo $data['start_date'];?>" placeholder="2013-06-21">
                            <?php if($_POST['save'] && !$start_date) { ?>
                                <span class="help-inline">Please correct the error</span>
                            <?php } ?>
                        </div>
                    </div>
                </div>
                <div class="span4">
                    <div class="control-group">
                        <label class="control-label" for="inputEndDate">End Date</label>
                        <div class="controls">
                            <input type="date" name="finish_date" id="inputEndDate" value="<?php echo $data['finish_date'];?>" placeholder="2013-06-21">
                        </div>
                    </div>
                </div>
            </div>
            <div class="control-group">
                <label class="control-label" for="inputArchitect">Architect</label>
                <div class="controls">
                    <select id="inputArchitect" name="architect" >
                        <?php while($row = mysqli_fetch_assoc($architects)){ ?>
                            <option <?php if($row['id'] == $data["architect_id"]) echo 'selected="true"'; ?> value="<?php echo $row['id']; ?>"><?php echo $row['name']; ?></option>
                        <?php } ?>
                    </select>
                </div>
            </div>
            <div class="control-group" data-upload-wrapper="images">
                <label class="control-label">Images</label>
                <div class="input-append">
                    <span class="input-upload">
                        <input class="span3" data-upload-text="field" type="text">
                        <button class="btn" type="button">Upload</button>
                        <input type="file" name="images[]" data-upload="field">
                    </span>
                    <div id="moreImages" data-add-upload="images" class="btn"><i class="icon-plus-sign"></i></div>
                </div>
            </div>
            <div>
                <?php while($image = mysqli_fetch_assoc($images)){?>
                    <img src="upload/<?php echo $image['name']; ?>" width="200px" class="img-polaroid" />
                <?php } ?>
            </div>
            <div class="control-group <?php if($_POST['save'] && !$cost) echo "error"; ?>">
                <label class="control-label" for="inputCost">Cost</label>
                <div class="controls">
                    <div class="input-prepend input-append">
                        <span class="add-on">$</span>
                        <input class="span2" name="cost" id="inputCost" value="<?php echo $data['cost'];?>" type="text">
                        <span class="add-on">.00</span>
                    </div>
                    <?php if($_POST['save'] && !$cost) { ?>
                        <span class="help-inline">Please correct the error</span>
                    <?php } ?>
                </div>
            </div>
        </div>
        <div class="text-right">
            <hr />
            <button type="submit" name="save" value="1" class="btn btn-primary">Save</button>
            <button type="reset" class="btn btn-warning">Clear</button>
        </div>
        </form>
    </section>
    <footer>
        <hr />
        <p>&copy; Company 2013</p>
    </footer>
</div>
<script src="http://code.jquery.com/jquery.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/default.js"></script>
</body>
</html>